<?php

namespace app\install\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\Url;

class Index extends Controller
{
    public function index()
    {
        return $this->fetch();
    }

    public function install(Request $request) {
        /* 判断密码是否相等 */
        if(($request->param("password") != $request->param("repassword"))
        || ($request->param("db_password") != $request->param("db_repassword"))) {
            $this->error("两个密码不相等");
        }



        $infoPath = APP_PATH . $request->module() . DS . 'data';
        $configFileName = 'config.php';
        $databaseFileName = 'database.php';
        $installFileName = 'install.sql';

        /* 替换database.php */
        $databaseFileStr = file_get_contents($infoPath . DS . $databaseFileName);
        $databaseFileStr = str_replace("{HOSTNAME}", $request->param("host"), $databaseFileStr);
        $databaseFileStr = str_replace("{DATABASE}", $request->param("database"), $databaseFileStr);
        $databaseFileStr = str_replace("{USERNAME}", $request->param("db_account"), $databaseFileStr);
        $databaseFileStr = str_replace("{PASSWORD}", $request->param("db_password"), $databaseFileStr);
        $databaseFileStr = str_replace("{HOSTPORT}", $request->param("port"), $databaseFileStr);
        file_put_contents(APP_PATH . $databaseFileName, $databaseFileStr);

        /* 设置数据库配置 */
        config("database.hostname", $request->param("host"));
        config("database.database", $request->param("database"));
        config("database.username", $request->param("db_account"));
        config("database.password", $request->param("db_password"));
        config("database.hostport", $request->param("port"));


        /* 替换config.php */
        $configFileStr = file_get_contents($infoPath . DS . $configFileName);
        $configFileStr = str_replace("{SALT}", $request->param("salt"), $configFileStr);
        file_put_contents(APP_PATH . $configFileName, $configFileStr);

        /* 替换install.sql */
        $installFileStr = file_get_contents($infoPath . DS . $installFileName);
        $installFileStr = str_replace("{ROOT}",$request->param("account"),$installFileStr);
        $installFileStr = str_replace("{PASSWORD}",$request->param("salt") . $request->param("password"),$installFileStr);
        $this->execSqlStr($installFileStr);

        $this->success("安装成功", Url::build('admin/index/index'));
    }

    private function execSqlStr($str) {
        if($str) {
            $arr = explode(";",$str);

            foreach ($arr as $val) {
                $val = trim($val);
                if($val == '') {
                    continue;
                }
                Db::execute($val . ';');
            }
        }

    }
}
